﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Collections.ObjectModel;
using System.Windows.Media;
using System.Xml.Linq;
using Agnes.Core;
using Csla;
using Csla.Rules.CommonRules;
using DevExpress.XtraScheduler;
using Microsoft.Windows.Controls;
using AppointmentLabel = DevExpress.Xpf.Scheduler.AppointmentLabel;
using AppointmentStatus = DevExpress.Xpf.Scheduler.AppointmentStatus;
using SchedulerStorage = DevExpress.Xpf.Scheduler.SchedulerStorage;

namespace Agnes.TaskManager
{
    [Serializable]
    public class TaskManager : ModelBase<TaskManager>
    {
        #region 属性


        public ObservableCollection<Task> Roots { get; set; }

        /// <summary>
        /// 绑定日历列表的SchedularStorage
        /// </summary>
        public SchedulerStorage SchedulerStorage { get; set; }

        public static readonly PropertyInfo<Task> SelectedTaskProperty = RegisterProperty<Task>(c => c.SelectedTask);
        /// <summary>
        /// 选中的任务
        /// </summary>
        public Task SelectedTask
        {
            get { return GetProperty(SelectedTaskProperty); }
            set { SetProperty(SelectedTaskProperty, value); }
        }

        /// <summary>
        /// 包含叶子任务的集合
        /// </summary>
        public ObservableCollection<Task> LeafTasks { get; private set; }

        private string _file;

        #endregion

        #region 初始化

        /// <summary>
        /// 初始化
        /// </summary>
        public void InitTaskManager()
        {
            Roots = new ObservableCollection<Task>();
            Task task = Task.CreateAsChild();
            task.Subject = "我的任务";
            LeafTasks.Add(task);
            task.Childs.Add(Task.CreateAsChild());
            Roots.Add(task);

            AgnesServiceManager.AgnesSlnService.SlnOpenedHanlder += new EventHandler(AgnesSlnService_SlnOpenedHanlder);
            AgnesServiceManager.AgnesSlnService.SlnClosedHandler += new EventHandler(AgnesSlnService_SlnClosedHandler);
        }

        void AgnesSlnService_SlnClosedHandler(object sender, EventArgs e)
        {
            try
            {
                if (AgnesServiceManager.AgnesSlnService.CurrentSln == null)
                {
                    return;
                }
                Save();
                Roots[0].Childs.Clear();

                LeafTasks.Clear();
            }
            catch (Exception ex)
            {
                AgnesServiceManager.LogServ.Error("TaskManager--保存任务管理失败："+ex.Message);
            }
        }

        void AgnesSlnService_SlnOpenedHanlder(object sender, EventArgs e)
        {
            if (AgnesServiceManager.AgnesSlnService.CurrentSln == null)
            {
                return;
            }
            _file = Path.Combine(AgnesServiceManager.AgnesSlnService.CurrentSln.TempDir, "Data_TaskManager", "Tasks.xml");
            Load();
        }

        /// <summary>
        ///  加载状态
        /// </summary>
        private void LoadStatus()
        {
            SchedulerStorage.AppointmentStorage.Statuses.Clear();
            SchedulerStorage.AppointmentStorage.Statuses.Add(new AppointmentStatus((int)TaskStatus.Prepare,
                                                                                   Colors.CornflowerBlue, "未开始", "未开始"));
            SchedulerStorage.AppointmentStorage.Statuses.Add(new AppointmentStatus((AppointmentStatusType)TaskStatus.InProgress,
                                                                                   Colors.LimeGreen, "进行中", "进行中"));
            SchedulerStorage.AppointmentStorage.Statuses.Add(new AppointmentStatus((AppointmentStatusType)TaskStatus.Finished,
                                                                                   Colors.DarkGray, "已完成", "已完成"));
            SchedulerStorage.AppointmentStorage.Statuses.Add(new AppointmentStatus((AppointmentStatusType)TaskStatus.Abandon,
                                                                                   Colors.Gray, "已放弃", "已放弃"));

        }

        /// <summary>
        /// 加载标签
        /// </summary>
        public void LoadLabels()
        {
            SchedulerStorage.AppointmentStorage.Labels.Clear();
            string path = Path.Combine(AgnesServiceManager.AddInPath, "App\\TaskManager\\TaskLabels.xml");
            if (File.Exists(path))
            {
                XElement el = XElement.Load(path);
                foreach (XElement i in el.Elements("Label"))
                {
                    AppointmentLabel label =
                        new AppointmentLabel((Color)ColorConverter.ConvertFromString(i.Attribute("Color").Value),
                                             i.Attribute("DisplayName").Value, i.Attribute("DisplayName").Value);
                    SchedulerStorage.AppointmentStorage.Labels.Add(label);
                }
            }
        }

        /// <summary>
        /// 保存标签
        /// </summary>
        public void SaveLabels()
        {
            string path = Path.Combine(AgnesServiceManager.AddInPath, "App\\TaskManager\\TaskLabels.xml");
            if (!File.Exists(path))
            {
                File.Create(path).Close();
            }

            XElement el = new XElement("Labels");
            foreach (AppointmentLabel i in SchedulerStorage.AppointmentStorage.Labels)
            {
                XElement xElement = new XElement("Label",
                                                 new XAttribute("DisplayName", i.DisplayName),
                                                 new XAttribute("Color", i.Color));
                el.Add(xElement);
            }

            el.Save(path);
        }
        
        protected override void DoCreate(object createParam)
        {
            base.DoCreate(createParam);

            SchedulerStorage = new SchedulerStorage();

            LoadStatus();
            LoadLabels();

            using (BypassPropertyChecks)
            {
                SelectedTask = null;
                LeafTasks = new ObservableCollection<Task>();

            }
        }

        #endregion

        #region 公开方法

        /// <summary>
        /// 保存到文件
        /// </summary>
        public void Save()
        {
            if (!Directory.Exists(Path.Combine(AgnesServiceManager.AgnesSlnService.CurrentSln.TempDir, "Data_TaskManager")))
            { 
                Directory.CreateDirectory(Path.Combine(AgnesServiceManager.AgnesSlnService.CurrentSln.TempDir, "Data_TaskManager"));
            }
            if (!File.Exists(_file))
            {
                File.Create(_file).Close();
            }

            XElement el = new XElement("Tasks");

            foreach (Task i in Roots[0].Childs)
            {
                i.SaveToXml(el.Add);
            }

            el.Save(_file);
        }

        /// <summary>
        /// 从文件中加载
        /// </summary>
        public void Load()
        {
            Roots[0].Childs.Clear();
            LeafTasks.Clear();
            if (File.Exists(_file))
            {
                XElement el = XElement.Load(_file);
                foreach (XElement i in el.Elements("Task"))
                {
                    Roots[0].Childs.Add(Task.FetchAsChild(i));
                }
            }

            ReCalcLeafTasks();
            if (Roots[0].Childs.Count == 0)
            {
                Roots[0].Childs.Add(Task.CreateAsChild());
            }
        }

        private void ReCalcLeafTasks()
        {
            List<Task> tmp = new List<Task>();
            foreach (Task i in LeafTasks)
            {
                if (i.Childs.Count != 0)
                {
                    tmp.Add(i);
                }
            }

            foreach (Task i in tmp)
            {
                LeafTasks.Remove(i);
            }
        }

        #endregion
    }
}
